﻿<div id="surveyTitle">
    <label for="title">Survey Title</label>
    <input type="text" name="title" id="title" value="@ViewBag.SurveyTitle" class="text ui-widget-content ui-corner-all" />
</div>

<ul id="questions"></ul>

<button id="add">Add a new question</button>
<button id="publish">Finish & Publish this Survey</button>
<img id="loading" src="@Url.Content("~/Content/loading.gif")" alt="loading..." style="display:none;" />

<script type="text/javascript">
    $(function () {
        $('button#add').button({ icons: { primary: "ui-icon-circle-plus"} }).disableDuringAjax();
        $('button#publish').button({ icons: { primary: "ui-icon-circle-triangle-e"} }).disableDuringAjax();
        $.post('@ViewBag.QuestionsAjaxUrl', {}, function (response) {
            appendQuestions(response);
        }, 'json');
        var appendQuestions = function (questions) {
            if (questions == null && questions.length == 0) { return; }
            var tmplItems = $tmpl('#editQuestionsTemplate', questions, '#questions');
            for (var i in tmplItems) { bindEvents(tmplItems[i]); }
            $('#questions').sortable({
                beforeStop: resetHandleStyles,
                update: updateQuestionIndices,
                revert: true,
                placeholder: 'ui-state-highlight questionPlaceHolder',
                handle: '.handle'
            });
            updateQuestionIndices();
            $('#questions button').disableDuringAjax();
            $registerAjaxWaitingElement('img#loading');
            $('.page').trigger('resize');
        }
        var resetHandleStyles = function () {
            $('ul#questions .handle').removeClass('ui-state-hover').removeClass('ui-state-active');
        };
        var bindEvents = function (tmplItem) {
            tmplItem.on('edit', onEdit);
            tmplItem.on('delete', onDelete);
            tmplItem.on('moveUp', onMoveUp);
            tmplItem.on('moveDown', onMoveDown);
        };
        var onEdit = function (event, questionId, question, questionTmplItem) {
            var tmplItems = $tmpl(
                '#editQuestionTemplate',
                { questionId: questionId, question: question },
                '#' + $createContainer().attr('id'));
            tmplItems[0].trigger('showDialog', function (question) {
                questionTmplItem.trigger('update');
                bindEvents(questionTmplItem);
            });
        };
        var onDelete = function (event, questionId, question, tmplItem) {
            $confirm('Are you sure to delete this question?', function () {
                $(tmplItem.nodes).remove();
            });
        };
        var onMoveUp = function (event, questionId, question, tmplItem) {
            var prev = $(tmplItem.nodes).prev();
            $(tmplItem.nodes).insertBefore(prev);
            updateQuestionIndices();
        };
        var onMoveDown = function (event, questionId, question, tmplItem) {
            var next = $(tmplItem.nodes).next();
            $(tmplItem.nodes).insertAfter(next);
            updateQuestionIndices();
        };
        var updateQuestionIndices = function () {
            var titles = $('ul#questions > li');
            for (var i = 0; i < titles.length; i++) {
                var question = $(titles[i]).tmplItem().data;
                question.Index = i;
            }
        };
        var getQuestions = function () {
            var questions = [];
            $('ul#questions > li').each(function () {
                questions.push($(this).tmplItem().data);
            });
            return questions;
        };
        $('button#add').click(function () {
            var tmplItems = $tmpl(
                '#editQuestionTemplate', {
                    questionId: '',
                    question: {
                        QuestionId: '', Title: 'Title',
                        Options: ['The First Option', 'The Second Option', 'More Options...']
                    }
                }, '#' + $createContainer().attr('id'));
            tmplItems[0].trigger('showDialog', function (question) {
                $.post('@Url.Action("Create", "Question")', {
                    questionJsonString: JSON.stringify(question)
                }, function (response) {
                    question.QuestionId = response.QuestionId;
                    appendQuestions([question]);
                }, 'json');
            });
        });
        $('button#publish').click(function () {
            var questions = getQuestions();
            $.post('@Url.Action("Publish", "Survey")', {
                surveyId: '@ViewBag.SurveyId',
                title: $('#surveyTitle #title').val(),
                questions: JSON.stringify(questions)
            }, function (response) {
                document.location = response;
            });
        });
    });
</script>